package com.fivestar.pmanager.web.controller;


import com.fivestar.pmanager.constants.CommonConstants;
import com.fivestar.pmanager.core.base.BaseBean;
import com.fivestar.pmanager.core.base.PageBean;
import com.fivestar.pmanager.core.exception.DMLNoRecordEffectedException;
import com.fivestar.pmanager.core.util.ToolUtil;
import com.fivestar.pmanager.model.FsUserBean;
import com.fivestar.pmanager.service.SysRoleUserService;
import com.fivestar.pmanager.system.domain.CommonParameterBean;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.fivestar.pmanager.core.util.CodeHelper.isNull;
import static com.fivestar.pmanager.core.util.LoggerHelper.logError;

/**
 * 
 * 未涉及分页的模块直接继承此类
 * 
 */
@SuppressWarnings("all")
public abstract class BaseController extends MultiActionController implements
        CommonConstants
{

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    private static final String DEFAULT_ZERO = "0";

    @Autowired
    private SysRoleUserService sysRoleUserService;

    public BaseController()
    {

    }

    public String toString()
    {
        try
        {
            return BeanUtils.describe(this).toString();
        }
        catch (Exception e)
        {
            return e.getMessage();
        }
    }

    /**
     * 取得session对象
     */
    protected HttpSession getSession()
    {
        return getRequest().getSession();
    }

    /**
     * 取得request对象
     */
    protected HttpServletRequest getRequest()
    {
        return ToolUtil.getRequest();
    }


    /**
     * 获取当期登录的用户
     *
     * @return
     */
    protected FsUserBean getCurrUser()
    {
        return (FsUserBean) getSession().getAttribute(SESSION_KEY_SUPPORT_USER);
    }


    /**
     * 获取公共参数
     */
    protected CommonParameterBean getCommonParameter()
    {
        return (CommonParameterBean) getSession().getAttribute(SESSION_KEY_COMMON_PARAMTER);
    }


    /**
     * 清楚之前保存的查询条件
     */
    protected void clearSearchParameter(String sessionKey_)
    {
        if (!isKeepSearchParameter())
        {
            getSession().removeAttribute(sessionKey_);
        }
    }

    /**
     * 是否要保存查询条件
     */
    protected boolean isKeepSearchParameter()
    {
        String keepSP = getRequest().getParameter(PARAMETER_KEY_KEEP_SP);

        if (keepSP == null)
        {
            return false;
        }

        if ("Y".equals(keepSP.trim()))
        {
            return true;
        }
        return false;
    }
    
    protected String getProjectRealPath(String name)
    {
        return getServletContext().getRealPath(name);
    }

    /**
     * 设置查询参数至session
     */
    protected void setSearchParamToSession(BaseBean searchParam, PageBean pageBean)
    {
        try
        {
            BaseBean searchParamNew = searchParam.getClass().newInstance();
            if(searchParam != null) org.springframework.beans.BeanUtils.copyProperties(searchParam, searchParamNew);
            getSession().setAttribute(SESSION_KEY_SEARCH_PARAMS + "&" + getClass().getName(), searchParamNew);
            getSession().setAttribute(SESSION_KEY_SEARCH_PAGE_PARAMS + "&" + getClass().getName(), pageBean == null ? new PageBean() : pageBean);
        }
        catch (Exception e)
        {
            logError(logger, e);
        }

    }

    /**
     * 设置查询参数至session
     * 
     * @author fangsj
     * @return
     * @throws
     */
    protected void getSearchParamFromSession(BaseBean searchParam, PageBean pageParam)
    {

        try
        {
            BaseBean oldSearchParam = (BaseBean) getSession().getAttribute(SESSION_KEY_SEARCH_PARAMS + "&" + getClass().getName());
            PageBean oldPageParam = (PageBean) getSession().getAttribute(SESSION_KEY_SEARCH_PAGE_PARAMS + "&" + getClass().getName());

            if (oldSearchParam != null)
                org.springframework.beans.BeanUtils.copyProperties(oldSearchParam, searchParam);
            if (oldPageParam != null) org.springframework.beans.BeanUtils.copyProperties(oldPageParam, pageParam);
        }
        catch (Exception e)
        {
            logError(logger, e);
        }
    }

    /**
     * 获取上传文件
     * 
     * @author fangsj
     * @return
     * @throws
     */
    protected Map<String, MultipartFile> getUploadFileMap()
    {
        return getMultipartRequest().getFileMap();
    }
    
    
    /**
     * 获取上传文件
     * 
     * @author fangsj
     * @return
     * @throws
     */
    protected List<MultipartFile> getUploadFileList(String fileName)
    {
        return getMultipartRequest().getFiles(fileName);
    }
    
    
    /**
     * 获取MultipartHttpServletRequest
     *
     * @author fangsj
     * @return MultipartHttpServletRequest
     */
    protected MultipartHttpServletRequest getMultipartRequest()
    {
        return (DefaultMultipartHttpServletRequest) getRequest();
    }

    /**
     * 
     * 输出响应报文
     *
     * @author fangsj
     * @param response  
     * @param text 响应报文
     * @return
     * @throws
     */
    protected void outputResponse(HttpServletResponse response,String text)
    {
        try
        {
            response.setContentType("text/html;charst=UTF-8");
            
            PrintWriter writer = response.getWriter();
            writer.write(text);
            writer.flush();
            writer.close();
        }
        catch (IOException e)
        {
            logError(logger, e);
        }
    }
    
    
    protected String getMessage(String key, Object... values)
    {
        ApplicationContext contxt = WebApplicationContextUtils
                .getWebApplicationContext(getServletContext());
        return contxt.getMessage(key, values, Locale.CHINA);
    }

    protected String getMessage(String key, List<String> values)
    {
        ApplicationContext contxt = WebApplicationContextUtils
                .getWebApplicationContext(getServletContext());
        return contxt.getMessage(key, values.toArray(), Locale.CHINA);
    }

    protected String getMessage(String key)
    {
        ApplicationContext contxt = WebApplicationContextUtils
                .getWebApplicationContext(getServletContext());
        return contxt.getMessage(key, new Object[] {}, Locale.CHINA);
    }

    /**
     * 获得用户所有的角色
     *
     * @param userId
     * @return
     */
    protected String getUserAuthRoleIds()
    {
        return sysRoleUserService.getRoles(getCommonParameter().getActorId());
    }

}
